import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/stores/userStore'
import {
  reqGetCartList,
  reqUpdateChecked,
  reqCheckAllStatus,
  reqAddCart,
  reqDelCartGoods
} from '@/api/cart'

import { swiperCellBehavior } from '@/behaviors/swiperCell'
import { debounce } from 'miniprogram-licia'
import { modal, toast } from '@/utils/extendApi'

const computedBehavior = require('miniprogram-computed').behavior

ComponentWithStore({
  behaviors: [computedBehavior, swiperCellBehavior],
  storeBindings: {
    store: userStore,
    fields: ['token']
  },

  // 组件的初始数据
  data: {
    cartList: [],
    emptyDes: '还没有添加商品，快去添加吧～'
  },
  computed: {
    selectAllStatus(data) {
      return (
        data.cartList.length !== 0 && data.cartList.every((item) => item.isChecked === 1)
      )
    },
    totalPrice(data) {
      return data.cartList
        .filter((item) => item.isChecked)
        .reduce((prev, item) => {
          return prev + item.count * item.price
        }, 0)
    }
  },
  // 组件的方法列表
  methods: {
    toOrder() {
      if (this.data.totalPrice === 0) {
        toast({
          title: '请选择要购买的商品'
        })
        return
      }
      wx.navigateTo({
        url: '/modules/orderPayModule/pages/order/detail/detail'
      })
    },
    async showTipGetList() {
      if (!this.data.token) {
        this.setData({
          cartList: [],
          emptyDes: '您还未登录，登录以获得更多权益'
        })
        return
      }
      const { code, data: cartList } = await reqGetCartList()
      this.setData({
        cartList,
        emptyDes: cartList.length === 0 ? '还没有添加商品，快去添加吧～' : ''
      })
    },
    onShow() {
      this.showTipGetList()
    },
    async updateChecked(event) {
      console.log(event)
      const { detail } = event
      const { id, index } = event.target.dataset
      console.log(id)
      const isChecked = detail ? 1 : 0
      const res = await reqUpdateChecked(id, 1)
      if (res.code === 200) {
        this.setData({
          [`cartList[${index}].isChecked`]: isChecked
        })
      }
    },
    async selectAllStatus(event) {
      const { detail } = event
      console.log(detail)
      const isChecked = detail ? 1 : 0
      const res = await reqCheckAllStatus(isChecked)
      console.log(res)
      if (res.code === 200) {
        const newList = JSON.parse(JSON.stringify(this.data.cartList))
        newList.forEach((item) => (item.isChecked = isChecked))
        this.setData({
          cartList: newList
        })
      }
    },
    changeBuyNum: debounce(async function (event) {
      const newBuyNum = event.detail > 200 ? 200 : event.detail
      const { id, index, oldBuyNum } = event.target.dataset
      const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
      const regRes = reg.test(newBuyNum)
      //校验不通过
      if (!regRes) {
        this.setData({
          [`cartList[${index}].count`]: oldBuyNum
        })
        return
      }
      const disCount = newBuyNum - oldBuyNum

      if (!disCount) {
        return
      }
      const res = await reqAddCart({ goodsId: id, count: disCount })
      if (res.code === 200) {
        this.setData({
          [`cartList[${index}].count`]: newBuyNum,
          [`cartList[${index}].isChecked`]: 1
        })
      }
    }, 500),
    onHide() {
      this.onSwiperCellClickCommon()
    },
    async delCart(event) {
      const { id } = event.currentTarget.dataset
      const modalRes = await modal({
        content: '您确定要删除吗？'
      })
      if (!modalRes) return
      const res = await reqDelCartGoods(id)
      console.log(res)
      if (res.code === 200) {
        this.showTipGetList()
      }
    }
  }
})
